//package com.xust.oa.controller;
//
//
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.hankcs.hanlp.HanLP;
//import com.hankcs.hanlp.seg.common.Term;
//import com.xust.oa.domain.entity.Knowledge;
//import com.xust.oa.domain.entity.KnowledgeBase;
//import com.xust.oa.domain.entity.TermFreq;
//import com.xust.oa.domain.vo.UserVO;
//import com.xust.oa.service.KnowledgeBaseService;
//import com.xust.oa.service.KnowledgeService;
//import com.xust.oa.service.TermFreqService;
//import com.xust.oa.utils.JwtUtil;
//import com.xust.oa.utils.UserHolder;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//
//import static com.xust.oa.utils.SentenceSimilarityNew.cosineSimilarity;
//import static com.xust.oa.utils.SentenceSimilarityNew.getWordFrequencyVector;
//
//@RestController
//@RequestMapping("deepSeek")
//@Slf4j
//public class OpenAIController {
//    //    @Resource
////    private KnowledageService knowledageService; //本地知识库的录入
////    @Resource
////    private TermFreqService termFreqService; //热词的统计
//    @Value("${ai.config.deepseek.apiKey}")
//    private String API_KEY;
//    @Value("${ai.config.deepseek.baseUrl}")
//    private String API_URL;
//    // 用于保存每个用户的对话历史
//
//    private final Map<String, List<Map<String, String>>> sessionHistory = new
//            ConcurrentHashMap<>();
//    private final ExecutorService executorService = Executors.newCachedThreadPool();
//    private final ObjectMapper objectMapper = new ObjectMapper();
//
//    @Autowired
//    private KnowledgeBaseService knowledgeService;
//
//    @Autowired
//    private TermFreqService termFreqService;
//
//    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public SseEmitter chat(@RequestBody String question, HttpServletRequest httpServletRequest) {
//        Map<String, Integer> vec1 = getWordFrequencyVector(question);
//        List<KnowledgeBase> list = knowledgeService.list();
//        List<String> questionList = new ArrayList<>();
//        int flag=0;
//        String msg="";
//        for (KnowledgeBase knowledgeBase : list){
//            String sentence1 = knowledgeBase.getQuestion();
//            Map<String, Integer> vec2 = getWordFrequencyVector(sentence1);
//            double similarity = cosineSimilarity(vec1, vec2);
//            if (similarity>0.75){
//                flag=1;
//                msg=knowledgeBase.getAnswer();
//                break;
//            }
//        }
//
//
//
//        List<Term> termList = HanLP.segment(question);
//        for (Term term : termList) {
//            QueryWrapper<TermFreq> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("tag", term.word);
//            TermFreq one = termFreqService.getOne(queryWrapper);
//            if (one == null) {
//                TermFreq termFreq = new TermFreq();
//                termFreq.setTag(term.word);
//                termFreq.setCount(1);
//                termFreqService.save(termFreq);
//            } else {
//                one.setCount(one.getCount() + 1);
//                termFreqService.updateById(one);
//            }
//        }
//        //用户标识
////        UserVO user = UserHolder.getUser();
//        String userId="123";
////        if (user != null)
////         userId = user.getId(); // 或者从 token 中解析出用户 ID
////        else {
////            String token = httpServletRequest.getHeader("Access-Token");
////            userId = JwtUtil.getUserIdFromToken(token);
////        }
//        //Server send Events 服务器主动推送信息
//        SseEmitter emitter = new SseEmitter(-1L);
//        int finalFlag = flag;
//        String finalMsg = msg;
//        executorService.execute(() -> {
//            try {
//                log.info("流式回答开始, 问题: {}", question);
//                // 获取当前用户的对话历史
//                List<Map<String, String>> messages =
//                        sessionHistory.getOrDefault(userId, new ArrayList<>());
//                // 添加用户的新问题到对话历史
//                Map<String, String> userMessage = new HashMap<>();
//                userMessage.put("role", "user");
//                userMessage.put("content", question);
//                Map<String, String> systemMessage = new HashMap<>();
//                systemMessage.put("role", "system");
//                systemMessage.put("content", "华清远见西安中心");
//                messages.add(userMessage);
//                messages.add(systemMessage);
//                // 调用 Deepseek API
//                try (CloseableHttpClient client = HttpClients.createDefault()) {
//                    HttpPost request = new HttpPost(API_URL);
//                    request.setHeader("Content-Type", "application/json");
//                    request.setHeader("Authorization", "Bearer " + API_KEY);
//                    Map<String, Object> requestMap = new HashMap<>();
//                    requestMap.put("model", "deepseek-chat");
//                    requestMap.put("messages", messages); // 包含对话历史
//                    requestMap.put("stream", true);
//                    String requestBody = objectMapper.writeValueAsString(requestMap);
//                    request.setEntity(new StringEntity(requestBody,
//                            StandardCharsets.UTF_8));
//                    try (CloseableHttpResponse response = client.execute(request);
//                         BufferedReader reader = new BufferedReader(
//                                 new
//                                         InputStreamReader(response.getEntity().getContent(),
//                                         StandardCharsets.UTF_8))) {
//                        StringBuilder aiResponse = new StringBuilder();
//                        if (finalFlag ==1){
//                            aiResponse.append(finalMsg);
//                        }else {
//                        String line;
//                        while ((line = reader.readLine()) != null) {
//                            if (line.startsWith("data: ")) {
//                                System.err.println(line);
//                                String jsonData = line.substring(6);
//                                if ("[DONE]".equals(jsonData)) {
//                                    break;
//                                }
//                                JsonNode node = objectMapper.readTree(jsonData);
//                                String content = node.path("choices")
//                                        .path(0)
//                                        .path("delta")
//                                        .path("content")
//                                        .asText("");
//                                if (!content.isEmpty()) {
//                                    emitter.send(content);
//
//                                    aiResponse.append(content); // 收集 AI 的回复
//                                }
//                            }
//                        }
//                        }
//                        System.out.println("deepSeek的回答====>" + aiResponse.toString());
//                        // 将 AI 的回复添加到对话历史
//                        Map<String, String> aiMessage = new HashMap<>();
//                        aiMessage.put("role", "assistant");
//                        aiMessage.put("content", aiResponse.toString());
//                        messages.add(aiMessage);
//                        // 更新会话状态
//                        sessionHistory.put(userId, messages);
//                        log.info("流式回答结束, 问题: {}", question);
//                        //保存结果进入数据库
//
//                        QueryWrapper<KnowledgeBase> queryWrapper =new QueryWrapper<>();
//                        queryWrapper.eq("question",question);
//                        KnowledgeBase knowledgeBase = knowledgeService.getOne(queryWrapper);
//                        if (knowledgeBase==null){
//                           knowledgeBase = new KnowledgeBase();
//                            knowledgeBase.setQuestion(question);
//                            knowledgeBase.setAnswer(aiResponse.toString());
//                            knowledgeService.save(knowledgeBase);
//                        }else {
//                            knowledgeBase.setAnswer(aiResponse.toString());
//                            knowledgeService.updateById(knowledgeBase);
//                        }
//
//
//                        //表示已经推送玩所有的数据
//                        emitter.complete();
//                    }
//                } catch (
//                        Exception e) {
//                    log.error("处理 Deepseek 请求时发生错误", e);
//                    emitter.completeWithError(e);
//                }
//            } catch (Exception e) {
//                log.error("处理 Deepseek 请求时发生错误", e);
//                emitter.completeWithError(e);
//            }
//        });
//        return emitter;
//    }
//}